import Meta from "../../components/Meta";
import Header from "../../components/Header/Header";
import { request } from "../../utils/request";
import { Row, Col, Spin } from 'antd';
import React, { useEffect, useState, useMemo } from 'react';
import { Modal, Button, Select, Space, Popconfirm, message, InputNumber } from 'antd';
import { basePath } from "../../utils/tool";
import { ExclamationCircleOutlined } from '@ant-design/icons';
import router from "next/router";
export default function Mybag(props) {

  const [isModalVisible, setIsModalVisible] = useState(false);
  const [cartData, setCart] = useState([]);
  const [total, setTotal] = useState(0);
  const [curr,setCurr] = useState(null);
  const [loading,setItemLoading] = useState(false);
  const [units,setUnits] = useState([]);
  const [expressInfo,setExpressInfo] = useState(null);
  const [shippingFee,setShippingFee] = useState(0)
  // const showModal = () => {
  //   setIsModalVisible(true);
  // };
  const handleOk = () => {
    setIsModalVisible(false);
  };

  const handleCancel = () => {
    setIsModalVisible(false);
  };
  const { Option } = Select;

  function handleChange(value) {
    console.log(`selected ${value}`);
  }

  function confirm(e) {
    console.log(e);
    message.success('Click on Yes');
  }

  function cancel(e) {
    console.log(e);
    message.error('Click on No');
  }
  const getCartList = async () => {
    console.log('process', process.env.APIURL);
    const ret = await request(`${basePath()}/api/cart/list`);
    const tplList = await request(`${basePath()}/api/express/tplList`,{
      current:1,
      pageSize:20
    });
    const expressInfoRet = tplList.data.rows.find(item=>item.feeType === 2);
    setExpressInfo(expressInfoRet);
    if (ret.code === 100000) {
      setCart(ret.data)
      const total = ret.data.reduce((a, b) => {
        console.log('a.totalAmount', a)
        console.log('b', b)
        return parseFloat(a) + parseFloat(b.totalAmount)
      }, 0)
      
      const totalQty =  ret.data.reduce((a, b) => {
        console.log('a.totalAmount', a)
        console.log('b', b)
        return parseInt(a) + parseInt(b.qty)
      }, 0)
      console.log('totalQty',totalQty)
      let shipFee = 0;
      if(totalQty <= expressInfoRet.defaultUnit){
        setShippingFee(expressInfoRet.defaultFee)
        shipFee = expressInfoRet.defaultFee
      } else {
        setShippingFee(expressInfoRet.stepFee)
        shipFee = expressInfoRet.stepFee
      }
      setTotal((parseFloat(total) + parseFloat(shipFee)).toFixed(2))
      const obj = {
        amount:{
          value:total.toFixed(2),
          currency_code:"USD",
          breakdown:{
            item_total:{
              currency_code:"USD",
              value:total.toFixed(2)
            }
          }
        },
        items:[],
      }
      ret.data.forEach(item=>{
        obj.items.push({
          unit_amount:{
            currency_code:"USD",
            value:item.price,
          },
          quantity:item.qty,
          name:`${item.productName +'-'+item.sizeName + '-'+item.colorEnName}`
        })
      })
      console.log('obj',obj)
      setUnits([obj])
     

    } else {
      message.error('get bag list error')
    }
  }
 
  const handleClickSize = (index) => {
    const sku = props.goodsData.sku.find(item => item.color == props.colorData[colorIndex].id && item.size == props.sizeData[index].id);
    console.log('sku--size', sku)
    setSku(sku);
    setSizeIndex(index)
  }

  const handleClickColor = (index) => {
    const sku = props.goodsData.sku.find(item => item.color == props.colorData[index].id && item.size == props.sizeData[sizeIndex].id);
    setSku(sku);
    setColorIndex(index)
  }

  const handleClickImgPagi = (index) => {
    setImgIndex(index)
    console.log(swiperRef.current)
    swiperRef.current?.goTo(index);
  }
  const handleRemove = async (data) => {
    console.log('data', data)
    const ret = await request(`${basePath()}/api/cart/delete`, { id: data.cartId });
    if (ret.code === 100000) {
      getCartList()
    }
  }
  const handleChangQty = async(e,index)=>{
    setCurr(index)
    const cartId = cartData[index].cartId;
    const totalAmount = (e*cartData[index].price).toFixed(2)
    setItemLoading(true)
    const ret = await request(`${basePath()}/api/cart/update`, { id: cartId ,buyQty:e,totalAmount});
   
    if (ret.code === 100000) {
      getCartList()
      setItemLoading(false)
    } else {
      setItemLoading(false)
    }

  }

 const toCheckout = ()=>{
  console.log('list',cartData);
  localStorage.setItem('cartData',JSON.stringify(cartData))
  localStorage.setItem('shipFee',shippingFee)
  router.push('/shop/checkout');
 }
  useEffect(() => {
    getCartList()
  }, [])
  return (
    <div className="shop-myBag">
      <Meta>
        <title>NINAMOKA-Mybag</title>
      </Meta>
      <Header />

      <Row>
        <Col xs={1} md={2}></Col>
        <Col xs={22} md={20}>
          <Row>
            {/* 左边区域 */}
            <Col xs={24} md={16}>

              <h1 className="left-h1">My Bag ({cartData.length}Item)</h1>
              {
                cartData.map((item, index) => {
                  return (
                    <Spin spinning={loading && curr === index}>
                      <div className="left">

                        <div className="myBag">
                          <img className="left-img" src={item.goodsUrl}></img>
                          <div className="Stretch">
                            <h2 className="Stretch-h2">{item.productName}</h2>
                            <div className="Stretch-span-box">
                              <span className="Stretch-span">{item.colorEnName}</span>
                              <span className="Stretch-ONE">{item.sizeName}</span>
                             
                            </div>
                            <div className="size-box">
                              <div className="size">

                              </div>
                              <div className="itemPrice">
                                <span className="Stretch-span">itemPrice</span>
                                <a className="Stretch-span">${item.price}</a>
                              </div>
                              <div className="Quantity">
                                <span className="Stretch-span">Quantity</span>
                                <InputNumber step={1} min={1} defaultValue={item.qty} onChange={(e)=>handleChangQty(e,index)}/>
                              </div>
                              <div className="Total">
                                <span className="Stretch-span-total">Total Price</span>
                                <a className="Stretch-span">${item.totalAmount}</a>
                              </div>

                            </div>
                            <div className="Free-box">
                             
                              <div className="Save-box">
                                <a className="Save Free" onClick={() => {
                                  Modal.confirm({
                                    title: 'remove item',
                                    icon: <ExclamationCircleOutlined />,
                                    content: 'Are you sure you want to remove this item from your bag?',
                                    okText: 'Yes,Remove this item',
                                    cancelText: 'No,keep this item',
                                    onOk: () => handleRemove(item),
                                  });
                                }}>Remove</a>
                              </div>
                            </div>
                          </div>
                        </div>

                      </div>
                    </Spin>
                  )
                })
              }
            </Col>
            <Col xs={24} md={8}>
              <div className="right">
                <h1 className="left-h1">Order Summary</h1>
                <div className="Order-box">
                  <span className="Stretch-span">Subtotal</span>
                  <span className="Stretch-span">${total}</span>
                </div>
                <div className="Order-box">
                  <div className="Shipping">
                    <span className="Stretch-span Shipping-span">Shipping</span>
                  
                  </div>
                  <span className="Stretch-span">{shippingFee ? '$'+shippingFee : 'FREE'}</span>
                </div>
            
                <div className="Order-box Estimated">
                  <span className="Stretch-span">Total</span>
                  <span className="Stretch-span">USD {total}</span>
                </div>
              
                <Button type="primary" size="large" onClick={toCheckout}>CHECKOUT</Button>
                {/* <span className="Stretch-span checkout"> or checkout quickly with</span>shang
                <PayPalCheckoutButton units={units} /> */}
              </div>
            </Col>
          </Row>
        </Col>
        <Col xs={1} md={2}></Col>
      </Row>
      <Modal className="Modal-box" title="" visible={isModalVisible} onOk={handleOk} onCancel={handleCancel}>

        <div className="bag-left">
          <img className="bag-img" ></img>
          <div className="bag-box">
            <h1>Sun-proof jacket</h1>
            <span className="Swiftly-span"></span>
            <span className="Swiftly-span">$ </span>
            <div className="prop-box-header">
              <span className="Swiftly-span">Color:</span>
              {/* <span className="prop-box-header-content">{props.colorData[colorIndex].enName}</span> */}
            </div>
            <ul className="prop-box-content">
              {
                props.colorData && props.colorData.map((item, index) => (
                  <li
                    key={index}
                    className={colorIndex === index ? "li-color active" : 'li-color'}
                    onClick={() => handleClickColor(index)}
                    style={{ background: item.name }}
                  >
                    <span className="cricle"></span>
                  </li>
                ))
              }
            </ul>
            <div className="prop-box-header">
              <span className="Swiftly-span">Size:</span>
              {/* <span className="prop-box-header-content">{props.sizeData[sizeIndex].name}</span> */}
            </div>
            <ul className="prop-box-content">
              {
                props.sizeData && props.sizeData.map((item, index) => (
                  <li key={index} className={sizeIndex === index ? "li-size active" : 'li-size'} onClick={() => handleClickSize(index)}>{item.name}</li>
                ))
              }
            </ul>
            <Button className="bag-button">UPDATE ITEM</Button>
            <a className="bag-view">View product details</a>
          </div>
        </div>
      </Modal>

    </div>
  )
}

